#coding=utf-8
#LightCam VCS 
#init by hfh 20160219

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo

def gen_bank_link():
	banklink=[]
	try:
		comd="netstat -an|grep 52888|grep ESTABLISHED"
		#comd="cat /monitor/LightCam/temp/banklink.txt"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<6:
				continue
			else:
				info={
					'hostname':agent_hostname,
					'ipaddr':line.split()[4].split(':')[0]
				}
				banklink.append(info)
		#print banklink
		file=open("/monitor/LightCam/temp/banklink.json",'w')
		file.write(json.dumps(banklink))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		
def gen_member_link():
	memberlink=[]
	try:
		comd="netstat -an|grep 52666|grep ESTABLISHED"
		#comd="cat /monitor/LightCam/temp/memberlink.txt"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<6:
				continue
			else:
				info={
					'hostname':agent_hostname,
					'ipaddr':line.split()[4].split(':')[0]
				}
				memberlink.append(info)
		#print memberlink
		file=open("/monitor/LightCam/temp/memberlink.json",'w')
		file.write(json.dumps(memberlink))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		
def gen_portstatus(port):
	portstatus=[]
	try:
		comd="netstat -an|grep -w %s|grep ESTABLISHED|wc -l" % port
		#comd="cat /monitor/LightCam/temp/passcon.txt|grep 6006|grep ESTABLISHED|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		estab_con=popen.stdout.read()

		comd="netstat -an|grep -w %s|grep TIME_WAIT|wc -l" % port
		#comd="cat /monitor/LightCam/temp/passcon.txt|grep 6006|grep ESTABLISHED|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		twait_con=popen.stdout.read()

		info={
			'hostname':agent_hostname,
			'port':port,
			'estab_con':estab_con,
			'twait_con':twait_con
		}
		portstatus.append(info)
		
		file=open("/monitor/LightCam/temp/portstatus.json",'w')
		file.write(json.dumps(portstatus))
		file.close()
		
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

def gen_processstatus():
	processstatus=[]
	try:
		comd=r'''
			ps -fu trade|awk 'NR>1{$1=$2=$3=$4=$5=$6=$7="";print}'
		'''
		#comd=r'''
		#	cat /monitor/LightCam/temp/process.txt|awk 'NR>1{$1=$2=$3=$4=$5=$6=$7="";print}'
		#'''
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<3:
				continue
			info={
				'hostname':agent_hostname,
				'process':line.strip('\r\n ')
			}
			processstatus.append(info)
		#print processstatus
		file=open("/monitor/LightCam/temp/processstatus.json",'w')
		file.write(json.dumps(processstatus))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()
	
	#初始化数据库
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	dbname='lc_vcs'
	psisdb=db.useDatabase(dbname)
	
	while True:
		time.sleep(0.1)
		try:
			
			#进程状态统计
			gen_processstatus()
			
			#端口状态统计
			if agent_hostname in ('vcsbfrt1','vcsbfrt2'):
				gen_portstatus(52888)
			elif agent_hostname in ('vcsmfrt1','vcsmfrt2'):
				gen_portstatus(52666)
				
			#银行连接情况统计
			if agent_hostname in ('vcsbfrt1','vcsbfrt2'):
				gen_bank_link()
			
			#会员连接情况统计
			if agent_hostname in ('vcsmfrt1','vcsmfrt2'):
				gen_member_link()
				
			time.sleep(10)

		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
			time.sleep(10)
